package de.koller.balance.obj;

import de.koller.oceanFramework.math.RVec3;
import org.lwjgl.opengl.GL11;

public class FormableCube {

	private boolean init = false;
	
	/** oben: links vorne = 0m von oben im uhrzeigersinn
	 *  unten:links vorne = 4 */
	public final RVec3[] verteces = new RVec3[8];
	private final Face[]  faces = new Face[6];
	
	public FormableCube() {
		verteces[0] = new RVec3( -.5f,  .5f,  .5f );
		verteces[1] = new RVec3(  .5f,  .5f,  .5f );
		verteces[2] = new RVec3(  .5f,  .5f, -.5f );
		verteces[3] = new RVec3( -.5f,  .5f, -.5f );
		  
		verteces[4] = new RVec3( -.5f, -.5f,  .5f );
		verteces[5] = new RVec3(  .5f, -.5f,  .5f );
		verteces[6] = new RVec3(  .5f, -.5f, -.5f );
		verteces[7] = new RVec3( -.5f, -.5f, -.5f );
		
		faces[0] = new Face( 0, 4, 5, 1 );
		faces[1] = new Face( 1, 5, 6, 2 );
		faces[2] = new Face( 2, 6, 7, 3 );
		faces[3] = new Face( 3, 7, 4, 0 );
		faces[4] = new Face( 1, 2, 3, 0 );
		faces[5] = new Face( 4, 7, 6, 5 );
	}
	
	public void render() {
		for( int i = 0; i < faces.length; i++ )
			renderPolygon( i );
	}
	
	public void render( float x, float y, float z, float w, float h, float d ) {
		GL11.glPushMatrix();
		
		GL11.glTranslatef( x, y, z );
		GL11.glScalef( w, h, d );
		render();
		
		GL11.glPopMatrix();
	}
	
	private void renderPolygon( int faceIndex ) {
		if( faces[faceIndex] == null )
			return;
		
		GL11.glBegin( GL11.GL_QUADS );
		
		for( int i = 0; i < 4; i++ ) 
			renderVertex( i, faceIndex );
		
		GL11.glEnd();
	}
	
	private void renderVertex( int index, int faceIndex ) {
		RVec3 v = verteces[ faces[faceIndex].verteces[index] ];
		float[] uv = faces[ faceIndex ].uv[index];
		GL11.glTexCoord2f( uv[0], uv[1] );
		GL11.glVertex3f( v.x, v.y, v.z );
	}
	
	private static class Face {
		private final int[] verteces = new int[4];
		private final float[][] uv = new float[4][2];

		public Face( int v0, int v1, int v2, int v3 ) {
			uv[0][0] = 0; uv[0][1] = 0;
			uv[1][0] = 0; uv[1][1] = 1;
			uv[2][0] = 1; uv[2][1] = 1;
			uv[3][0] = 1; uv[3][1] = 0;
			
			verteces[0] = v0;
			verteces[1] = v1;
			verteces[2] = v2;
			verteces[3] = v3;
		}
	}
	
}
